package com.es.demo.controller;

import com.alibaba.fastjson.JSON;
import com.es.demo.pojo.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.rest.RestStatus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author zqf
 * @Date 2022/10/14 15:18
 * @Description: 修改doc
 */

@RestController("/update")
@Api(tags = "更新文档")
public class UpdateDocController {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    @Value("${elasticsearch.index}")
    private String esIndex;

    @GetMapping("/byid")
    @ApiOperation("根据id修改数据")
    public String updateDocument(@RequestParam("id") @ApiParam("id") String id,
                                 @RequestParam("name") @ApiParam("name,用来测试修改") String name) throws IOException {
        UpdateRequest request = new UpdateRequest(esIndex, id);

        User user = new User();
        user.setName(name);

        request.doc(JSON.toJSONString(user), XContentType.JSON);
        UpdateResponse response = restHighLevelClient.update(request, RequestOptions.DEFAULT);

        if (RestStatus.OK.equals(response.status())){
            return "更新成功";
        }
        return "更新失败";
    }

    @GetMapping("/batchUpdate")
    @ApiOperation("批量修改数据")
    public String updateDocument() throws IOException {
        List<User> userList = new ArrayList<>();
        BulkRequest bulkRequest = new BulkRequest();

        for (int i = 0; i < 10; i++) {
            User user = new User();
            user.setName("student batch " + i);
            user.setAge(i * 10);
            user.setAddress("贵阳市遵义市海龙镇");
            user.setTimes(System.currentTimeMillis());
            userList.add(user);
        }


        for (int i = 0; i < userList.size(); i++) {
            bulkRequest.add(new UpdateRequest(esIndex,i + "k").doc(JSON.toJSONString(userList.get(i)), XContentType.JSON));
        }

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);

        if (!bulk.hasFailures()){
            return "更新成功";
        }
        return "更新失败";
    }

}
